from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class Category(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name


class Tag(models.Model):
    name = models.CharField(max_length=30, unique=True)

    def __str__(self):
        return self.name


class Note(models.Model):
    PUBLIC = 'public'
    PROTECTED = 'protected'
    PRIVATE = 'private'

    PRIVACY_CHOICES = [
        (PUBLIC, '公开'),
        (PROTECTED, '仅关注用户可见'),
        (PRIVATE, '私密'),
    ]

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='notes')
    title = models.CharField(max_length=255)
    content = models.TextField()  # 可以扩展为富文本
    summary = models.TextField(blank=True, null=True)  # 摘要字段
    cover_image = models.ImageField(upload_to='covers/', blank=True, null=True)  # 封面图片字段

    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
    tags = models.ManyToManyField(Tag, blank=True)
    privacy = models.CharField(max_length=10, choices=PRIVACY_CHOICES, default=PUBLIC)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-created_at']  # 按创建时间降序排列


class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    note = models.ForeignKey(Note, on_delete=models.CASCADE, related_name='comments')
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE)
    likes = models.PositiveIntegerField(default=0)  # 点赞数量
    address = models.CharField(max_length=255, blank=True, null=True)  # 用户地址

    def __str__(self):
        return f'Comment by {self.user.username}'

    @property
    def is_root(self):
        return self.parent is None

    def can_delete(self, user):
        return self.user == user or self.note.user == user or user.is_staff

    class Meta:
        ordering = ['-created_at']


class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    note = models.ForeignKey(Note, on_delete=models.CASCADE, related_name='likes')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('user', 'note')  # 确保用户不能重复点赞
        ordering = ['-created_at']  # 按创建时间降序排列

    def __str__(self):
        return f'Like by {self.user.username}'
